<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #roleDescs="{ model, field }">
        <FormItemRest>
          <InputTextArea readonly v-model:value="model[field]" />
          <a-button
            @click="handleSuccessSelectRole({ codes: '', codeTexts: '' })"
            class="mt-2 mr-2"
          >
            清空
          </a-button>
          <a-button type="primary" @click="handleSelectRole" class="mt-2">选择</a-button>
        </FormItemRest>
      </template>
      <template #userRealNames="{ model, field }">
        <FormItemRest>
          <InputTextArea readonly v-model:value="model[field]" />
          <a-button @click="handleSuccessSelectUser(null)" class="mt-2 mr-2"> 清空 </a-button>
          <a-button type="primary" @click="handleSelectUser" class="mt-2">选择</a-button>
        </FormItemRest>
      </template>
      <template #filter="{ model, field }">
        <FormItemRest>
          <InputTextArea v-model:value="model[field]" />
          (注：条件不能以where及and开头，可以直接输入条件，也可以使用脚本，脚本中必须返回ret，ret中是条件语句)
          <a-button type="primary" @click="handleDesign" class="mt-2">设计器</a-button>
        </FormItemRest>
      </template>

      <template #aheadDay="{ model, field }">
        <FormItemRest>
          <div class="flex items-center gap-2">
            <InputNumber style="width: 100px !important" v-model:value="model[field]" />天
            <InputNumber style="width: 100px !important" v-model:value="dataRef['aheadHour']" />小时
            <InputNumber
              style="width: 100px !important"
              v-model:value="dataRef['aheadMinute']"
            />分钟
          </div>
        </FormItemRest>
      </template>
      <template #title="{ model, field }">
        <FormItemRest>
          <div class="flex items-center gap-2">
            <Input style="flex: 1" v-model:value="model[field]" />可以用{$字段名}来引用表单中的字段
          </div>
        </FormItemRest>
      </template>
      <template #content="{ model, field }">
        <FormItemRest>
          <div class="flex items-center gap-2">
            <InputTextArea
              style="flex: 1"
              v-model:value="model[field]"
            />可以用{$字段名}来引用表单中的字段
          </div>
        </FormItemRest>
      </template>

      <template #way>
        <FormItemRest>
          <Checkbox v-model:checked="dataRef['isMsg']">消息</Checkbox>
          <Checkbox v-model:checked="dataRef['isEmail']">邮件</Checkbox>
        </FormItemRest>
      </template>
    </BasicForm>
    <SelectUser @register="registerModalSelectUser" @success="handleSuccessSelectUser" />
    <SelectRoleModal @register="registerModalSelectRole" @success="handleSuccessSelectRole" />
    <DesignIframe
      ref="ifrmRef"
      @register="registerDesignIframeView"
      @success="handleSuccessDesignIframe"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onUnmounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './expirationReminder.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Checkbox, Input, InputNumber, Form } from 'ant-design-vue';
  import { SelectUser } from '/@/components/CustomComp/index';
  import SelectRoleModal from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/nodeEdit/modules/SelectRoleModal.vue';
  import DesignIframe from '/@/views/system/workflow/formManagement/eventDesign/modules/DesignIframe.vue';
  import { useModal } from '/@/components/Modal';
  import {
    getFormCreateRemind,
    getFormEditRemindPage,
    getFormUpdateRemind,
    getFormListTable,
    getFormGetTableFields,
  } from '/@/api/formDesign/formDesign';
  import { isArray } from '/@/utils/is';
  import { convertCamelToSnake } from '/@/utils/utils';
  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    name: 'ExpirationReminderDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Checkbox,
      Input,
      InputNumber,
      InputTextArea: Input.TextArea,
      FormItemRest: Form.ItemRest,
      SelectUser,
      SelectRoleModal,
      DesignIframe,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<Recordable>({});
      const userStore = useUserStore();

      const [
        registerForm,
        { resetFields, setFieldsValue, validate, updateSchema, getFieldsValue },
      ] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = data?.isUpdate;
        getTablesData();
        if (unref(isUpdate)) {
          const res = await getFormEditRemindPage({ id: data.record.id });
          dataRef.value = {
            ...res,
            isMsg: res.isMsg == 1 ? true : false,
            isEmail: res.isEmail == 1 ? true : false,
          };
          setFieldsValue({
            ...unref(dataRef),
          });
        } else {
          dataRef.value = data?.record || {};
          dataRef.value.isMsg = true;
          dataRef.value.isEmail = true;
          setFieldsValue({
            ...unref(dataRef),
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          let formData = Object.assign({}, unref(dataRef), values);
          formData.isMsg = formData.isMsg ? 1 : 0;
          formData.isEmail = formData.isEmail ? 1 : 0;
          formData = convertCamelToSnake(formData);
          formData.users = formData.user_names;
          formData.roles = formData.role_codes;
          const { name } = userStore.getUserInfo || {};
          formData.user_name = name;
          setDrawerProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            await getFormCreateRemind(formData);
          } else {
            await getFormUpdateRemind(formData);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      const [registerModalSelectUser, { openModal: openSelectUser }] = useModal();
      //选择用户
      const handleSelectUser = () => {
        let users: Recordable[] = [];
        if (dataRef.value.userNames) {
          const userNames: String[] = dataRef.value.userNames.split(',');
          const userRealNames: String[] = dataRef.value.userRealNames.split(',');
          userNames.forEach((item, index) => {
            users.push({
              name: item,
              key: item,
              realName: userRealNames[index],
              title: userRealNames[index],
            });
          });
        }
        openSelectUser(true, {
          users,
        });
      };
      //选择用户回调
      const handleSuccessSelectUser = (users: Recordable[]) => {
        if (users && users.length) {
          let userNames: String[] = [];
          let keys: String[] = [];

          users.forEach((item) => {
            userNames.push(item.title);
            keys.push(item.key);
          });
          dataRef.value.userRealNames = userNames.join(',');
          dataRef.value.userNames = keys.join(',');
          setFieldsValue({ userRealNames: dataRef.value.userRealNames });
        } else {
          dataRef.value.userRealNames = '';
          dataRef.value.userNames = '';
          setFieldsValue({ userRealNames: dataRef.value.userRealNames });
        }
      };

      //选择角色
      const [registerModalSelectRole, { openModal: openSelectRole }] = useModal();
      //选择角色
      const handleSelectRole = () => {
        let targetKeys = [];
        if (dataRef.value.roleCodes) {
          targetKeys = dataRef.value?.roleCodes ? dataRef.value.roleCodes.split(',') : [];
        }
        openSelectRole(true, {
          record: {
            targetKeys,
          },
        });
      };
      //选择角色回调
      const handleSuccessSelectRole = ({ codes, codeTexts }) => {
        dataRef.value.roleCodes = codes;
        dataRef.value.roleDescs = codeTexts;
        setFieldsValue({
          roleDescs: dataRef.value.roleDescs,
        });
      };

      //获取表名
      const tableDataSource = ref<Recordable[]>([]);
      const getTablesData = async () => {
        try {
          tableDataSource.value = [];
          const res = await getFormListTable();
          if (isArray(res)) {
            res.forEach((item) => {
              tableDataSource.value.push({
                label: item.name,
                value: item.code,
              });
            });
            updateSchema([
              {
                field: 'tableName',
                componentProps: {
                  options: tableDataSource.value,
                  showSearch: true,
                  optionFilterProp: 'label',
                  onChange: handleChangeTables,
                  // fieldNames: { label: '', value: '' },
                },
              },
            ]);
            if (!unref(isUpdate)) {
              const curRecord = tableDataSource.value.find(
                (item) => item.value.indexOf(dataRef.value.code) != -1,
              );
              if (curRecord) {
                setFieldsValue({ tableName: curRecord.value });
                handleChangeTables(curRecord.value);
              } else {
                setFieldsValue({ tableName: tableDataSource.value[0].value });
                handleChangeTables(tableDataSource.value[0].value);
              }
            } else {
              if (dataRef.value.tableName) {
                handleChangeTables(dataRef.value.tableName);
              }
            }
          }
        } catch (err) {
          console.error('getTablesDta', err);
        }
      };
      //表名change
      const handleChangeTables = (val) => {
        dataRef.value.tableName = val;
        getFieldsData();
      };
      const fieldsDataOptions = ref<Recordable[]>([]);
      //获取表对应字段
      const getFieldsData = async () => {
        try {
          const params = {
            tableName: dataRef.value.tableName,
          };
          fieldsDataOptions.value = [];
          const res = (await getFormGetTableFields(params)) || [];
          if (isArray(res)) {
            res.forEach((item) => {
              fieldsDataOptions.value.push({
                label: item.name,
                value: item.field,
              });
            });
            updateSchema([
              {
                field: 'dateField',
                componentProps: {
                  options: fieldsDataOptions.value,
                  showSearch: true,
                  optionFilterProp: 'label',
                },
              },
              {
                field: 'userField',
                componentProps: {
                  options: fieldsDataOptions.value,
                  showSearch: true,
                  optionFilterProp: 'label',
                },
              },
            ]);
            if (!unref(isUpdate)) {
              const record = getFieldsValue();
              if (record.dateField) {
                setFieldsValue({ dateField: '' });
              }
              if (record.userField) {
                setFieldsValue({ userField: '' });
              }
            }
          }
        } catch (err) {
          console.error(err);
        }
      };

      const [registerDesignIframeView, { openModal: openModalDesignIframeView, closeModal }] =
        useModal();
      //打开设计器
      const handleDesign = () => {
        const filter = getFieldsValue()?.filter;
        openModalDesignIframeView(true, {
          scriptStr: filter,
        });
      };
      const handleSuccessDesignIframe = (value) => {
        setFieldsValue({ filter: value });
      };

      const ifrmRef = ref<any>(null);
      let ideUrl = 'script_frame.jsp';
      const onMessage = (e) => {
        const filter = getFieldsValue()?.filter;
        var d = e.data;
        var data = d.data;
        var type = d.type;
        if (type == 'setScript') {
          setFieldsValue({ filter: data });
          if (d.cwsToken != null) {
            let cwsToken = d.cwsToken;
            ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
          }
          closeModal();
        } else if (type == 'getScript') {
          let serverInfo = userStore.getServerInfo;
          let data = {
            type: 'openerScript',
            version: serverInfo.version,
            spVersion: serverInfo.spVersion,
            scene: 'form.remind',
            data: filter,
          };
          // window.postMessage(data, '*');
          unref(ifrmRef).doPostMessage(data);
        } else if (type == 'setCwsToken') {
          let cwsToken = d.cwsToken;
          ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
        }
      };

      if (window.addEventListener) {
        window.addEventListener('message', onMessage, false);
      }
      onUnmounted(() => {
        window.removeEventListener('message', onMessage, false);
      });
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        registerModalSelectUser,
        handleSelectUser,
        handleSuccessSelectUser,
        dataRef,
        handleDesign,
        registerModalSelectRole,
        handleSuccessSelectRole,
        handleSelectRole,
        registerDesignIframeView,
        handleSuccessDesignIframe,
        ifrmRef,
      };
    },
  });
</script>
